package com.example.common.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.example.common.enetiy.AccessLog;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;

/**
 * Http 请求分析工具
 * @author qwert
 * @version 1.0.0
 * @create 2025/8/19 23:22
 **/
public class HttpAnalysisUtil {

    private static final UserAgentAnalyzer USER_AGENT_ANALYZER = UserAgentAnalyzer.newBuilder()
            .hideMatcherLoadStats()
            .withCache(10000)
            .build();

    /**
     * 构建访问日志实体
     */
    public static AccessLog buildAccessLog(ServletRequest request) {
        HttpServletRequest servletRequest = (HttpServletRequest) request;

        AccessLog log = new AccessLog();
        log.setTimestamp(System.currentTimeMillis());
//        log.setShortUrl(shortUrl);
//        log.setOriginalUrl(originalUrl);

        // IP 信息
        log.setIp(getClientIp(servletRequest));

        // 用户代理信息
        String userAgentStr = servletRequest.getHeader("User-Agent");
        if (userAgentStr != null) {
            UserAgent agent = USER_AGENT_ANALYZER.parse(userAgentStr);
            log.setBrowser(agent.getValue("AgentName"));
            log.setBrowserVersion(agent.getValue("AgentVersion"));
            log.setOperatingSystem(agent.getValue("OperatingSystemNameVersion"));
            log.setDeviceType(agent.getValue("DeviceName"));
//            log.setUserAgent(userAgentStr);
        }

        // 网络和设备信息
        log.setDeviceCategory(getDeviceCategory(userAgentStr));
        log.setNetworkType(getNetworkType(userAgentStr));

        // 地理位置信息（可选，需结合 IP 库）
        log.setCountry(getCountryFromIp(log.getIp()));

        return log;
    }

    /**
     * 获取客户端 IP
     */
    private static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (isEmptyOrUnknown(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (isEmptyOrUnknown(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    private static boolean isEmptyOrUnknown(String ip) {
        return ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip);
    }

    /**
     * 判断设备类型
     */
    private static String getDeviceCategory(String userAgent) {
        if (userAgent == null) return "Unknown";
        String ua = userAgent.toLowerCase();
        if (ua.contains("mobile") || ua.contains("android") || ua.contains("iphone")) {
            return "Mobile";
        } else if (ua.contains("tablet")) {
            return "Tablet";
        } else {
            return "Desktop";
        }
    }

    /**
     * 简单网络类型判断
     */
    private static String getNetworkType(String userAgent) {
        if (userAgent == null) return "Unknown";
        String ua = userAgent.toLowerCase();
        if (ua.contains("wifi")) {
            return "WiFi";
        } else if (ua.contains("mobile")) {
            return "Mobile";
        } else {
            return "Broadband";
        }
    }

    /**
     * 获取国家（占位，可结合 GeoIP2 / IP2Region）
     */
    private static String getCountryFromIp(String ip) {
        // TODO: 集成 MaxMind GeoIP2 或 IP2Region 实现
        return "Unknown";
    }

    /**
     * 获取网站ico
     */
    public static String getFaviconFromApi(String url) {
        String res = HttpUtil.get("https://v2.xxapi.cn/api/ico?url=" + url);
        JSONObject jsonObject = JSONObject.parseObject(res);
        Object icoUrl = jsonObject.get("data");
        return icoUrl.toString();
//        try {
//            URI uri = new URI(url);
//            String res = HttpUtil.get("http://www.google.com/s2/favicons?domain=" + uri.getHost());
//            JSONObject jsonObject = JSONObject.parseObject(res);
//            Object icoUrl = jsonObject.get("data");
//            return icoUrl.toString();
//        } catch (URISyntaxException e) {
//            throw new RuntimeException(e);
//        }

    }
}
